package com.matto1990.app.madlab.util;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.matto1990.app.madlab.R;
import com.matto1990.app.madlab.service.SyncService;
import com.matto1990.app.madlab.ui.HomeActivity;

public class TitlebarActivity extends Activity {
    public static final String STATE = "state";
    public State state;
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // First try and get the state from a previous instance
        state = (State) getLastNonConfigurationInstance();
        // If nothing create a new one and get the status
        if (state == null) {
            state = new State();
            final Intent intent = new Intent(SyncService.ACTION_STATUS, null, getApplicationContext(), SyncService.class);
            startService(intent);
        }
    }
    
    @Override
    public void onResume() {
        super.onResume();
        registerReceiver(startReceiver, new IntentFilter(SyncService.BROADCAST_START));
        registerReceiver(finishReceiver, new IntentFilter(SyncService.BROADCAST_FINISH));
        registerReceiver(statusReceiver, new IntentFilter(SyncService.BROADCAST_STATUS));
    }
    @Override
    public void onPause() {
        super.onPause();
        unregisterReceiver(startReceiver);
        unregisterReceiver(finishReceiver);
        unregisterReceiver(statusReceiver);
    }

    
    @Override
    public Object onRetainNonConfigurationInstance() {
        // Clear any strong references to this Activity, we'll reattach to
        // handle events on the other side.
        return state;
    }
    
    public void setupTitlebar() {
        // Do its thing
        if (state != null) {
            // Start listening for SyncService updates again
            updateRefreshStatus();
        }
        else {
            state = new State();
        }
        
        // Set click on logo to go to home activity
        TextView logoButton = (TextView) findViewById(R.id.title_logo);
        logoButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                final Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
                startActivity(intent);
            }
        });
        
        // Set the refresh button action
        ImageButton refreshButton = (ImageButton) findViewById(R.id.btn_title_refresh);
        refreshButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                // trigger off background sync
                final Intent intent = new Intent(Intent.ACTION_SYNC, null, getApplicationContext(), SyncService.class);
                // Tell the service that you want to recieve status of the sync
                // Fire off the intent!
                startService(intent);
            }
        });
        
        // Set the search button action
        // TODO: Make the search button work
        // ImageButton searchButton = (ImageButton) findViewById(R.id.btn_title_search);
    }
    
    private BroadcastReceiver startReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            state.syncing = true;
            updateRefreshStatus();
        }
    };
    
    private BroadcastReceiver finishReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            switch (intent.getIntExtra(SyncService.STATUS, -1)) {
            // The sync has finished
            case SyncService.STATUS_SYNC_FINISHED:
                state.syncing = false;
                updateRefreshStatus();
                break;
            // The sync errored!
            case SyncService.STATUS_SYNC_ERROR:
                // Error happened down in SyncService, show as toast.
                state.syncing = false;
                updateRefreshStatus();
                // TODO: Move to strings.xml
                final String errorText = "Error while syncing data :- " + intent.getStringExtra(Intent.EXTRA_TEXT);
                // Show the toast
                Toast.makeText(getApplicationContext(), errorText, Toast.LENGTH_LONG).show();
                break;
            }
        }
    };
    
    private BroadcastReceiver statusReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            state.syncing = intent.getIntExtra(SyncService.STATUS, SyncService.STATUS_NOT_RUNNING) == SyncService.STATUS_RUNNING;
            updateRefreshStatus();
        }
    };
    
    // Update the visibility of the refresh button and progress
    private void updateRefreshStatus() {
        // If syncing make the refresh button disappear
        findViewById(R.id.btn_title_refresh).setVisibility(state.syncing ? View.GONE : View.VISIBLE);
        // If syncing make the progress spinner visible
        findViewById(R.id.title_refresh_progress).setVisibility(state.syncing ? View.VISIBLE : View.GONE);
    }
    
    /**
     * State specific to {@link HomeActivity} that is held between configuration
     * changes. Any strong {@link Activity} references <strong>must</strong> be
     * cleared before {@link #onRetainNonConfigurationInstance()}, and this
     * class should remain {@code static class}.
     * 
     * Modified from the GoogleIO aplication by matto1990
     */
    public static class State implements Parcelable {
        public boolean syncing = false;

        @Override
        public int describeContents() {
            return 0;
        }

        @Override
        public void writeToParcel(Parcel out, int flags) {
            Bundle temp = new Bundle();
            temp.putBoolean("syncing", syncing);
            out.writeBundle(temp);
        }
        
        public static final Parcelable.Creator<State> CREATOR = new Parcelable.Creator<State>() {
            public State createFromParcel(Parcel in) {
                return new State(in);
            }
        
            public State[] newArray(int size) {
                return new State[size];
            }
        };
        
        private State(Parcel in) {
            Bundle temp = in.readBundle();
            syncing = temp.getBoolean("syncing");
        }

        public State() {
            
        }
    }
}
